//
//  CTMessageViewController.m
//  ConstellationTalk_0.1
//
//  Created by riley on 15/5/14.
//  Copyright (c) 2015年 riley chu. All rights reserved.
//

#import "CTMessageViewController.h"
#import "CTTabBarController.h"
#import "CTMessageDetailWebViewController.h"
#import "CTUserViewController.h"
#import "CTCommentViewController.h"
#import "CTSubjectDetailViewController.h"

//config
#import "CTHeader.h"

//view
#import "CTMessageView.h"

//function
#import "CTDebugManager.h"
#import "CTDataGenerator.h"
#import "CTGenRequestData.h"
#import "CTActivitorView.h"
#import "CTRemindView.h"
#import "CTAppLanguage.h"
#import "CTDeviceFunction.h"
#import "MobClick.h"

//logic
#import "CTMessageLogic.h"

//model
#import "CTDiscoveryItems.h"



static NSInteger messageFlipNumber = 0;



@interface CTMessageViewController ()<CTMessageViewDelegate,CTMessageLogicDelegate,UIAlertViewDelegate>
{
    CTMessageView * messageView;
    CTMessageLogic * messageLogic;
    
    CTMessageListItem * currentDeletePersonalMessageItem;
    CTOfficialMessageItem * currentDeleteOfficialMessageItem;
    
    CTActivitorView * acView;
    CTRemindView * remindView;
}
@end

@implementation CTMessageViewController

- (void)dealloc
{
    [acView removeFromSuperview];
    acView = nil;
    
    [remindView removeFromSuperview];
    remindView = nil;
    
    [messageView removeFromSuperview];
    messageView = nil;
    messageView.delegate = nil;
    
    messageLogic = nil;
    messageLogic.delegate = nil;
    
    messageView.delegate = nil;
    
    currentDeletePersonalMessageItem = nil;
    currentDeleteOfficialMessageItem = nil;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CTLoginSuccessNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CTExitSuccessNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CTPushNotification object:nil];
    
    [CTDebugManager showDebugLogInfo:@"dealloc : CTMessageViewController Is Removed!!!"];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        messageLogic = [[CTMessageLogic alloc] init];
        messageLogic.delegate = self;
        
        //注册登录&退出
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess:) name:CTLoginSuccessNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitSuccess:) name:CTExitSuccessNotification object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushNotiMesg:) name:CTPushNotification object:nil];
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //统计
    [MobClick beginLogPageView:@"CTMessageViewController"];
    //清除通知角标
    [CTDeviceFunction clearNotiBadgeNumber];
    
    [messageView viewWillShow];
     messageView.personalMessageListArr = [CTDataGenerator generatePersonalMessageListItems];
     messageView.officialMessageListArr = [CTDataGenerator generateOfficialMessageListItems];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    //统计
    [MobClick endLogPageView:@"CTMessageViewController"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    messageView = [[CTMessageView alloc] init];
    messageView.delegate = self;
    [self.view addSubview:messageView];
    
    messageFlipNumber = 1;
    [self sendPersonalMessageListRequest];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - request -

-(void)sendPersonalMessageListRequest
{
    [messageLogic messageListRequest:[CTGenRequestData genRequestMessageListItemWithFlipNumber:messageFlipNumber] successCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            messageView.personalMessageListArr = [CTDataGenerator generatePersonalMessageListItems];
            
            [messageView refreshPullDownEnd];
        });
    } failedHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
             messageView.personalMessageListArr = [CTDataGenerator generatePersonalMessageListItems];
            
            [messageView refreshPullDownEnd];
        });
    }];
}

-(void)sendMessageDeleteRequest
{
    acView = [[CTActivitorView alloc] init];
    [acView showActivitorViewOn:self.view withType:CTActivitorViewLongShadow];
    
    [messageLogic messageDeleteRequest:[CTGenRequestData genRequestMessageDeleteItem:currentDeletePersonalMessageItem] successCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [acView removeActivitorView];
            acView = nil;
           
            messageFlipNumber = 1;
            [self sendPersonalMessageListRequest];
        });
    } failedHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [acView removeActivitorView];
            acView = nil;
            messageView.personalMessageListArr = [CTDataGenerator generatePersonalMessageListItems];
            
        });
    }];
    
}






#pragma mark - messageView delegate -

-(void)refreshPersonalMesgControlPullDown:(CTMessageView *)view
{
    messageFlipNumber = 1;
    [self sendPersonalMessageListRequest];
}
-(void)refreshPersonalMesgControlPullUp:(CTMessageView *)view
{
    messageFlipNumber ++;
    [self sendPersonalMessageListRequest];
}

-(void)personalImageClicked:(CTMessageView *)view withItem:(CTMessageListItem *)itm
{
    
    CTTabBarController * tabbarVC = (CTTabBarController *)self.navigationController.tabBarController;
    [tabbarVC hideTabbarWithAnimate:YES];
    
    CTCommentViewController * commentVC = [[CTCommentViewController alloc] init];
    commentVC.scheme_id = itm.scheme_id;
    commentVC.levelType = CTCommentViewControllerLevelsFirst;
    [self.navigationController pushViewController:commentVC animated:YES];
}


-(void)clearAction:(CTMessageView *)view withType:(CTMessageViewType)type
{
    
    if (type == CTMessageViewTypePersonal) {
       // [messageLogic clearAllMessageData:CTMessageLogicTypePersonal];
    }else{
        
        if ([CTDataGenerator generateOfficialMessageListItems].count == 0) {
            
            remindView = [[CTRemindView alloc] init];
            [remindView showRemindViewOn:self.view withRemindWord:@"当前没有数据可以清空哦!"];
            
        }else{
            
            UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"确定要清空消息吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alertView show];
            
        }
    }
    return;
    
    
    
    
//    
//    NSMutableDictionary * indic = [NSMutableDictionary dictionaryWithCapacity:0];
//    NSMutableDictionary * ininDic = [NSMutableDictionary dictionaryWithCapacity:0];
//    
//    int i = arc4random() % 20000 ;
//    
//    [ininDic setObject:@"24600" forKey:@"key"];
//    [ininDic setObject:@"2" forKey:@"message_type"];
//    [ininDic setObject:[NSString stringWithFormat:@"%ld",(long)i]forKey:@"notice_id" ];
//    [ininDic setObject:@"http://buckets21.oss-cn-qingdao.aliyuncs.com/thumb_f7f1ce4a46beced6155c1aa79a27483b.jpeg" forKey:@"send_avatar"];
//    [ininDic setObject:[NSString stringWithFormat:@"%ld",(long)i] forKey:@"send_name"];
//    [ininDic setObject:@"1356363600" forKey:@"send_time"];
//    [ininDic setObject:@"10049" forKey:@"send_uid"];
//    [ininDic setObject:@"2" forKey:@"type"];
//    
//    
//    [indic setObject:@"系统运营通知，谢谢你的热情款待，谢谢你的热情款待" forKey:@"content"];
//    [indic setObject:ininDic forKey:@"extras"];
//    
//
//    
//    //存入数据库
//    [messageLogic addMessageData:indic];
//    
}

-(void)selectPersonalMessageItemAction:(CTMessageView *)view withItem:(CTMessageListItem *)itm
{
    if ([itm.type isEqualToString:@"1"]) {
        //点赞
        CTTabBarController * tabbarVC = (CTTabBarController *)self.navigationController.tabBarController;
        [tabbarVC hideTabbarWithAnimate:YES];
        CTUserViewController * userVC = [[CTUserViewController alloc] init];
        userVC.pushType = CTUserViewControllerPushFromTypeOther;
        userVC.levelType = CTUserViewControllerLevelFirst;
        userVC.userUid = itm.user.uid;
        [self.navigationController pushViewController:userVC animated:YES];
        
    }else if([itm.type isEqualToString:@"2"]){
        //关注
        CTTabBarController * tabbarVC = (CTTabBarController *)self.navigationController.tabBarController;
        [tabbarVC hideTabbarWithAnimate:YES];
        CTUserViewController * userVC = [[CTUserViewController alloc] init];
        userVC.pushType = CTUserViewControllerPushFromTypeOther;
        userVC.levelType = CTUserViewControllerLevelFirst;
        userVC.userUid = itm.user.uid;
        [self.navigationController pushViewController:userVC animated:YES];
        
    }else if ([itm.type isEqualToString:@"3"]){
        //评论
        CTTabBarController * tabbarVC = (CTTabBarController *)self.navigationController.tabBarController;
        [tabbarVC hideTabbarWithAnimate:YES];
        CTUserViewController * userVC = [[CTUserViewController alloc] init];
        userVC.pushType = CTUserViewControllerPushFromTypeOther;
        userVC.levelType = CTUserViewControllerLevelFirst;
        userVC.userUid = itm.user.uid;
        [self.navigationController pushViewController:userVC animated:YES];
        
    }else{
        
    }
}
-(void)removePersonalMessageItemAction:(CTMessageView *)view withItem:(CTMessageListItem *)itm
{
    currentDeletePersonalMessageItem = itm;
    [self sendMessageDeleteRequest];
}
-(void)selectOfficialMessageItemAction:(CTMessageView *)view withItem:(CTOfficialMessageItem *)itm
{
    if ([itm.extras.type isEqualToString:@"1"]) {
        //网址，运营人员推送
        
        CTTabBarController * tabbarVC = (CTTabBarController *)self.navigationController.tabBarController;
        [tabbarVC hideTabbarWithAnimate:YES];
        
        CTMessageDetailWebViewController * messageDetailVC = [[CTMessageDetailWebViewController alloc] init];
        messageDetailVC.item = itm;
        [self.navigationController pushViewController:messageDetailVC animated:YES];
        
    }else if([itm.extras.type isEqualToString:@"2"]){
        //专题
        
        CTHotSpotsItem * hotSpotItem = [[CTHotSpotsItem alloc] init];
        hotSpotItem.group_id = itm.extras.key;
        hotSpotItem.hotspot_name = @"";
        
        CTTabBarController * tabbarVC = (CTTabBarController *)self.navigationController.tabBarController;
        [tabbarVC hideTabbarWithAnimate:YES];
        
        CTSubjectDetailViewController * subjectDetailVC = [[CTSubjectDetailViewController alloc] init];
        subjectDetailVC.hotSpotsItem = hotSpotItem;
        [self.navigationController pushViewController:subjectDetailVC animated:YES];
        hotSpotItem = nil;
        
        
    }else if ([itm.extras.type isEqualToString:@"3"]){
        //热点
        CTTopic * topicItem = [[CTTopic alloc] init];
        topicItem.group_id = itm.extras.key;
        topicItem.topic = @"";
        
        [[NSNotificationCenter defaultCenter] postNotificationName:CT_NOTI_JUMP_TO_GROUP object:topicItem];
        
        CTTabBarController * tabbarVC = (CTTabBarController *)self.navigationController.tabBarController;
        [tabbarVC showTabbarWithAnimate:YES];
        [tabbarVC selectTabbarIndex:0];
        
        topicItem = nil;
        
    }else{
        
    }
}
-(void)removeOfficialMessageItemAction:(CTMessageView *)view withItem:(CTOfficialMessageItem *)itm
{
    currentDeleteOfficialMessageItem = itm;
    [messageLogic deleteMessageData:CTMessageLogicTypeOfficial withNoticeID:itm.extras.notice_id];
}



#pragma mark - message logic delegate -

-(void)personalMessageReceiveSuccessed
{
    messageView.personalMessageListArr = [CTDataGenerator generatePersonalMessageListItems];
}

-(void)personalMessageRemoveSuccessed
{
    messageView.personalMessageListArr = [CTDataGenerator generatePersonalMessageListItems];
}



-(void)officialMessageReceiveSuccessed
{
    messageView.officialMessageListArr = [CTDataGenerator generateOfficialMessageListItems];
}
-(void)officialMessageRemoveSuccessed
{
    messageView.officialMessageListArr = [CTDataGenerator generateOfficialMessageListItems];
}



-(void)clearMessageScuueed:(CTMessageLogicType)type
{
    if (type == CTMessageLogicTypePersonal) {
         messageView.personalMessageListArr = [CTDataGenerator generatePersonalMessageListItems];
    }else{
         messageView.officialMessageListArr = [CTDataGenerator generateOfficialMessageListItems];
    }
}






//临时数组的删除与增加回调
-(void)mesgTemporaryAdded
{
    
}
-(void)mesgTemporaryRemoved
{
   
}

-(void)pushNotiMesg:(id)sender
{
    NSNotification * noti = (NSNotification *)sender;
    NSDictionary * info = noti.userInfo;
    NSDictionary * extrasDic = [info objectForKey:@"extras"];
    NSString * message_type = [NSString stringWithFormat:@"%@",[extrasDic objectForKey:@"message_type"]];
    
    if ([message_type isEqualToString:@"1"]) {
        //个人消息
        messageFlipNumber = 1;
        [self sendPersonalMessageListRequest];
    }else{
        //官方
    }
}




#pragma mark - alert delegate -
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [messageLogic clearAllMessageData:CTMessageLogicTypeOfficial];
        alertView = nil;
    }
}


#pragma mark - login & exit -

-(void)loginSuccess:(id)sender
{
    messageFlipNumber = 1;
    [self sendPersonalMessageListRequest];
    
    messageView.officialMessageListArr = [CTDataGenerator generateOfficialMessageListItems];
}
-(void)exitSuccess:(id)sender
{
    messageView.officialMessageListArr = [CTDataGenerator generateOfficialMessageListItems];
}

@end
